class Solution {
public:
    TreeNode* pre = NULL;
    TreeNode* ret = NULL;
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        if(!root){
            return NULL;
        }
        inorderSuccessor(root->left,p);
        
        if(pre && ret){
            return ret;
        } 
        if(pre && !ret){
            ret = root;
        }
        if(!pre && root->val == p->val){
            pre = root;
        }
        
        inorderSuccessor(root->right,p);
        
        return ret;
    }
};
